/*
 * Created by JFormDesigner on Tue Apr 04 20:55:02 CST 2023
 */

import cn.hutool.core.util.StrUtil;
import com.creditcode.xxj.constant.CreditCodeConstants;
import com.creditcode.xxj.util.CustomCreditCodeUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.util.Objects;

/**
 * @author Administrator
 */
public class CreditCodeFrame extends JFrame {

    public static final String NEED_VALIDATE_PLACEHOLDER = "请在此处输入18位统一社会信用代码";

    public static void main (String[] args) {
        CreditCodeFrame creditCodeFrame = new CreditCodeFrame();
        creditCodeFrame.createUIComponents();
        creditCodeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        creditCodeFrame.setVisible(true);
    }

    public CreditCodeFrame () {
        initComponents();
    }

    public void createUIComponents() {
        ComboBoxModel<String[]> model = new DefaultComboBoxModel<>(CreditCodeConstants.DJGLBM_CODE_STR_ARR);
        setCheckBoxModel(djglbmList,model);

        djglbmList.setSelectedIndex(0);
        final String[] selectedItem = (String[]) djglbmList.getSelectedItem();
        ComboBoxModel<String[]> modelJglb =
                new DefaultComboBoxModel<>(CreditCodeConstants.jglbMap.get(selectedItem[0]));
        setCheckBoxModel(jglbList,modelJglb);
        needValidateCreditCode.setText(NEED_VALIDATE_PLACEHOLDER);
    }

    private void setCheckBoxModel(JComboBox<String[]> checkBoxModel,ComboBoxModel<String[]> comboBoxModel){
        checkBoxModel.setModel(comboBoxModel);
        checkBoxModel.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value,
                                                          int index, boolean isSelected, boolean cellHasFocus) {
                if (value instanceof String[]) {
                    // 如果值是字符串数组，则显示数组的第二个元素（即名称）
                    value = ((String[])value)[1];
                }
                return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            }
        });
        checkBoxModel.setToolTipText(((String[]) Objects.requireNonNull(checkBoxModel.getSelectedItem()))[1]);
    }

    private void jglbListItemStateChanged(ItemEvent e) {
        final String[] item = (String[]) e.getItem();
        jglbList.setToolTipText(((String[]) Objects.requireNonNull(item))[1]);
    }

    private void djglbmListItemStateChanged(ItemEvent e) {
        final String[] item = (String[]) e.getItem();
        ComboBoxModel<String[]> model = new DefaultComboBoxModel<>(CreditCodeConstants.jglbMap.get(item[0]));
        setCheckBoxModel(jglbList,model);
    }

    private void buildCreditCode(ActionEvent e) {
        if (StrUtil.isNotBlank(creditCodePrintText.getText())){
            creditCodePrintText.removeAll();
        }
        final String[] djglbmListSelectedItem = (String[]) djglbmList.getSelectedItem();
        final String[] jglbListSelectedItem = (String[]) jglbList.getSelectedItem();
        creditCodePrintText.setText(CustomCreditCodeUtils.randomCreditCode(djglbmListSelectedItem[0],
                jglbListSelectedItem[0]));
    }

    private void validateCreditCode(ActionEvent e) {
        final String needValidateCreditCodeText = needValidateCreditCode.getText();
        if (StrUtil.isBlank(needValidateCreditCodeText)){
            validateCreditCodeResult.setText("请输入要校验的统一社会信用代码");
            return;
        }
        if (needValidateCreditCodeText.length() != 18){
            validateCreditCodeResult.setText("校验失败，请输入18位长度的统一社会信用代码");
            return;
        }
        validateCreditCodeResult.setText(CustomCreditCodeUtils.isCreditCode(needValidateCreditCodeText));
    }

    private void needValidateCreditCodeFocusGained(FocusEvent e) {
        // 获取焦点时，如果文本是提示语，则清空让用户手动输入要校验的值
        if (NEED_VALIDATE_PLACEHOLDER.equals(needValidateCreditCode.getText())) {
            needValidateCreditCode.setText(StrUtil.EMPTY);
        }
    }

    private void needValidateCreditCodeFocusLost(FocusEvent e) {
        // 失去焦点时，如果内容为空，则输入提示语
        if (StrUtil.isBlank(needValidateCreditCode.getText())){
            needValidateCreditCode.setText(NEED_VALIDATE_PLACEHOLDER);
        }
    }

    private void clearneedValidateCreditCode(ActionEvent e) {
        if (StrUtil.isNotBlank(needValidateCreditCode.getText())){
            needValidateCreditCode.setText(StrUtil.EMPTY);
        }
        needValidateCreditCodeFocusLost(null);
    }

    private void copyClickEvent(ActionEvent e) {
        StringSelection stringSelection = new StringSelection(creditCodePrintText.getText());
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        // Generated using JFormDesigner Evaluation license - unknown
        buildCreditCode = new JPanel();
        djglbmTitle = new JLabel();
        djglbmList = new JComboBox();
        jggllbTitle = new JLabel();
        jglbList = new JComboBox();
        buildCreditCodeButton = new JButton();
        scrollPane1 = new JScrollPane();
        creditCodePrintText = new JEditorPane();
        copyButton = new JButton();
        validateCreditCode = new JPanel();
        validateCreditCodeButton = new JButton();
        scrollPane2 = new JScrollPane();
        needValidateCreditCode = new JEditorPane();
        validateCreditCodeResult = new JEditorPane();
        clearneedValidateCreditCodeButton = new JButton();

        //======== this ========
        setTitle("\u6cd5\u4eba\u548c\u5176\u4ed6\u7ec4\u7ec7\u7edf\u4e00\u793e\u4f1a\u4fe1\u7528\u4ee3\u7801\u751f\u6210\u5668");
        setResizable(false);
        Container contentPane = getContentPane();

        //======== buildCreditCode ========
        {
            buildCreditCode.setBorder ( new javax . swing. border .CompoundBorder ( new javax . swing. border .TitledBorder ( new javax . swing. border .EmptyBorder
            ( 0, 0 ,0 , 0) ,  "JFor\u006dDesi\u0067ner \u0045valu\u0061tion" , javax. swing .border . TitledBorder. CENTER ,javax . swing. border
            .TitledBorder . BOTTOM, new java. awt .Font ( "Dia\u006cog", java .awt . Font. BOLD ,12 ) ,java . awt
            . Color .red ) ,buildCreditCode. getBorder () ) ); buildCreditCode. addPropertyChangeListener( new java. beans .PropertyChangeListener ( ){ @Override public void
            propertyChange (java . beans. PropertyChangeEvent e) { if( "bord\u0065r" .equals ( e. getPropertyName () ) )throw new RuntimeException( )
            ;} } );

            //---- djglbmTitle ----
            djglbmTitle.setText("\u9009\u62e9\u767b\u8bb0\u7ba1\u7406\u90e8\u95e8:");
            djglbmTitle.setFont(new Font("\u5b8b\u4f53", Font.BOLD, 14));

            //---- djglbmList ----
            djglbmList.addItemListener(e -> djglbmListItemStateChanged(e));

            //---- jggllbTitle ----
            jggllbTitle.setText("\u9009\u62e9\u673a\u6784\u7c7b\u522b:");
            jggllbTitle.setFont(new Font("\u5b8b\u4f53", Font.BOLD, 14));

            //---- jglbList ----
            jglbList.addItemListener(e -> jglbListItemStateChanged(e));

            //---- buildCreditCodeButton ----
            buildCreditCodeButton.setText("\u751f\u6210\u7edf\u4e00\u793e\u4f1a\u4fe1\u7528\u4ee3\u7801");
            buildCreditCodeButton.setFont(new Font("\u5b8b\u4f53", Font.BOLD, 14));
            buildCreditCodeButton.addActionListener(e -> buildCreditCode(e));

            //======== scrollPane1 ========
            {

                //---- creditCodePrintText ----
                creditCodePrintText.setEditable(false);
                scrollPane1.setViewportView(creditCodePrintText);
            }

            //---- copyButton ----
            copyButton.setText("\u590d\u5236");
            copyButton.setFont(new Font("\u5b8b\u4f53", Font.BOLD, 14));
            copyButton.addActionListener(e -> copyClickEvent(e));

            GroupLayout buildCreditCodeLayout = new GroupLayout(buildCreditCode);
            buildCreditCode.setLayout(buildCreditCodeLayout);
            buildCreditCodeLayout.setHorizontalGroup(
                buildCreditCodeLayout.createParallelGroup()
                    .addGroup(buildCreditCodeLayout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addGroup(buildCreditCodeLayout.createParallelGroup()
                            .addGroup(buildCreditCodeLayout.createSequentialGroup()
                                .addComponent(djglbmTitle)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(djglbmList, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE))
                            .addGroup(buildCreditCodeLayout.createSequentialGroup()
                                .addComponent(buildCreditCodeButton)
                                .addGap(18, 18, 18)
                                .addComponent(copyButton, GroupLayout.PREFERRED_SIZE, 70, GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(buildCreditCodeLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                            .addGroup(buildCreditCodeLayout.createSequentialGroup()
                                .addComponent(jggllbTitle)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jglbList, GroupLayout.PREFERRED_SIZE, 160, GroupLayout.PREFERRED_SIZE))
                            .addComponent(scrollPane1, GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE))
                        .addContainerGap(27, Short.MAX_VALUE))
            );
            buildCreditCodeLayout.setVerticalGroup(
                buildCreditCodeLayout.createParallelGroup()
                    .addGroup(buildCreditCodeLayout.createSequentialGroup()
                        .addGroup(buildCreditCodeLayout.createParallelGroup()
                            .addGroup(buildCreditCodeLayout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(buildCreditCodeLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(djglbmTitle)
                                    .addComponent(djglbmList, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
                            .addGroup(GroupLayout.Alignment.TRAILING, buildCreditCodeLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(buildCreditCodeLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(jggllbTitle)
                                    .addComponent(jglbList, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
                        .addGroup(buildCreditCodeLayout.createParallelGroup()
                            .addGroup(buildCreditCodeLayout.createSequentialGroup()
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                                .addGroup(buildCreditCodeLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                    .addComponent(buildCreditCodeButton)
                                    .addComponent(copyButton))
                                .addGap(35, 35, 35))
                            .addGroup(buildCreditCodeLayout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 61, GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(26, Short.MAX_VALUE))))
            );
        }

        //======== validateCreditCode ========
        {

            //---- validateCreditCodeButton ----
            validateCreditCodeButton.setText("\u6821\u9a8c");
            validateCreditCodeButton.setFont(new Font("\u5b8b\u4f53", Font.BOLD, 14));
            validateCreditCodeButton.addActionListener(e -> validateCreditCode(e));

            //======== scrollPane2 ========
            {

                //---- needValidateCreditCode ----
                needValidateCreditCode.addFocusListener(new FocusAdapter() {
                    @Override
                    public void focusGained(FocusEvent e) {
                        needValidateCreditCodeFocusGained(e);
                    }
                    @Override
                    public void focusLost(FocusEvent e) {
                        needValidateCreditCodeFocusLost(e);
                    }
                });
                scrollPane2.setViewportView(needValidateCreditCode);
            }

            //---- validateCreditCodeResult ----
            validateCreditCodeResult.setEditable(false);
            validateCreditCodeResult.setFont(new Font("JetBrains Mono", Font.PLAIN, 18));

            //---- clearneedValidateCreditCodeButton ----
            clearneedValidateCreditCodeButton.setText("\u6e05\u7a7a");
            clearneedValidateCreditCodeButton.setFont(new Font("\u5b8b\u4f53", Font.BOLD, 14));
            clearneedValidateCreditCodeButton.addActionListener(e -> clearneedValidateCreditCode(e));

            GroupLayout validateCreditCodeLayout = new GroupLayout(validateCreditCode);
            validateCreditCode.setLayout(validateCreditCodeLayout);
            validateCreditCodeLayout.setHorizontalGroup(
                validateCreditCodeLayout.createParallelGroup()
                    .addGroup(validateCreditCodeLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(validateCreditCodeLayout.createParallelGroup()
                            .addComponent(validateCreditCodeResult, GroupLayout.PREFERRED_SIZE, 577, GroupLayout.PREFERRED_SIZE)
                            .addGroup(validateCreditCodeLayout.createSequentialGroup()
                                .addComponent(scrollPane2, GroupLayout.PREFERRED_SIZE, 281, GroupLayout.PREFERRED_SIZE)
                                .addGap(58, 58, 58)
                                .addComponent(validateCreditCodeButton, GroupLayout.PREFERRED_SIZE, 86, GroupLayout.PREFERRED_SIZE)
                                .addGap(37, 37, 37)
                                .addComponent(clearneedValidateCreditCodeButton, GroupLayout.PREFERRED_SIZE, 86, GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            validateCreditCodeLayout.setVerticalGroup(
                validateCreditCodeLayout.createParallelGroup()
                    .addGroup(GroupLayout.Alignment.TRAILING, validateCreditCodeLayout.createSequentialGroup()
                        .addContainerGap(15, Short.MAX_VALUE)
                        .addGroup(validateCreditCodeLayout.createParallelGroup()
                            .addGroup(GroupLayout.Alignment.TRAILING, validateCreditCodeLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(validateCreditCodeButton)
                                .addComponent(clearneedValidateCreditCodeButton))
                            .addComponent(scrollPane2, GroupLayout.Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE))
                        .addGap(31, 31, 31)
                        .addComponent(validateCreditCodeResult, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
                        .addGap(17, 17, 17))
            );
        }

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addGap(3, 3, 3)
                    .addGroup(contentPaneLayout.createParallelGroup()
                        .addGroup(contentPaneLayout.createSequentialGroup()
                            .addComponent(validateCreditCode, GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE)
                            .addGap(16, 16, 16))
                        .addComponent(buildCreditCode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        contentPaneLayout.setVerticalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addComponent(buildCreditCode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(validateCreditCode, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    // Generated using JFormDesigner Evaluation license - unknown
    private JPanel buildCreditCode;
    private JLabel djglbmTitle;
    private JComboBox djglbmList;
    private JLabel jggllbTitle;
    private JComboBox jglbList;
    private JButton buildCreditCodeButton;
    private JScrollPane scrollPane1;
    private JEditorPane creditCodePrintText;
    private JButton copyButton;
    private JPanel validateCreditCode;
    private JButton validateCreditCodeButton;
    private JScrollPane scrollPane2;
    private JEditorPane needValidateCreditCode;
    private JEditorPane validateCreditCodeResult;
    private JButton clearneedValidateCreditCodeButton;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}
